{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 批量化提取占位信息并绘制图像\n",
    "\n",
    "# 批量提取每个体系的占位数据到对应文件夹下的YSITE-T_output.xlsx表格中,并给予图区的数据进行绘图"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 注:\n",
    "\n",
    "需要更改的内容如下:\n",
    "\n",
    "#设置根目录路径\n",
    "root_directory = r'F:\\MCMFData\\机器学习专项\\吴波\\数据库'\n",
    "\n",
    "其他:\n",
    "\n",
    "这两部分开运行:\n",
    "\n",
    "第一步：处理EXP文件并保存为Excel\n",
    "\n",
    "第二步：在需要时执行绘图\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "import os\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import re\n",
    "import numpy as np\n",
    "\n",
    "\n",
    "def process_exp_file(file_path):\n",
    "    data = {}\n",
    "    current_column = None\n",
    "\n",
    "    with open(file_path, 'r') as file:\n",
    "        for line in file:\n",
    "            if '$ PLOTTED COLUMNS ARE' in line:\n",
    "                match = re.search(r'Y\\(FCC,([A-Za-z#0-9]+)\\)', line)\n",
    "                if match:\n",
    "                    current_column = match.group(1)\n",
    "                    if current_column not in data:\n",
    "                        data[current_column] = {'T': [], 'Value': []}\n",
    "            else:\n",
    "                if current_column:\n",
    "                    parts = line.split()\n",
    "                    if len(parts) >= 2:\n",
    "                        try:\n",
    "                            temperature = float(parts[0])\n",
    "                            value = float(parts[1])\n",
    "                            data[current_column]['T'].append(temperature)\n",
    "                            data[current_column]['Value'].append(np.float32(value))\n",
    "                        except ValueError:\n",
    "                            pass\n",
    "\n",
    "    # 创建一个 DataFrame 列表\n",
    "    dfs = []\n",
    "    for col, values in data.items():\n",
    "        df = pd.DataFrame(values)\n",
    "        df.columns = ['T', col]\n",
    "        df = df.drop_duplicates(subset='T')  # 去除重复的 'T' 值\n",
    "        dfs.append(df.set_index('T'))\n",
    "\n",
    "    # 使用 pd.concat 合并所有 DataFrame\n",
    "    combined_data = pd.concat(dfs, axis=1).reset_index()\n",
    "\n",
    "    return combined_data\n",
    "\n",
    "\n",
    "def process_exp_and_save_excel(root_dir):\n",
    "    # 遍历root_dir下的所有文件夹\n",
    "    for subdir, dirs, files in os.walk(root_dir):\n",
    "        for file in files:\n",
    "            # 检查文件名是否为YSITE-T.EXP（不区分大小写）\n",
    "            if file.lower() == 'ysite-t.exp':\n",
    "                exp_file_path = os.path.join(subdir, file)\n",
    "                # 检查文件是否为空\n",
    "                if os.path.getsize(exp_file_path) < 10 * 1024:\n",
    "                    print(f\"Skipping small file: {exp_file_path}\")\n",
    "                    continue  # 跳过小于10KB的文件\n",
    "                print(f\"Processing {exp_file_path}\")\n",
    "\n",
    "                # 处理EXP文件并保存为Excel\n",
    "                save_exp_as_excel(exp_file_path, subdir)\n",
    "\n",
    "\n",
    "def save_exp_as_excel(exp_file_path, subdir):\n",
    "    processed_data = process_exp_file(exp_file_path)\n",
    "    processed_data = processed_data.iloc[2:-1]\n",
    "    processed_data.sort_values(by='T', ascending=True, inplace=True)\n",
    "    processed_data.drop_duplicates(subset='T', inplace=True)\n",
    "\n",
    "    # 保存处理后的数据到Excel文件\n",
    "    output_excel_path = os.path.join(subdir, 'YSITE-T_output.xlsx')\n",
    "    processed_data.to_excel(output_excel_path, index=False)\n",
    "    print(f\"Data processed and saved to {output_excel_path}\")\n",
    "\n",
    "\n",
    "def plot_from_excel_and_save(root_dir):\n",
    "    # 遍历root_dir下的所有子目录\n",
    "    for subdir, dirs, files in os.walk(root_dir):\n",
    "        for file in files:\n",
    "            # 检查文件名是否为处理后的Excel文件\n",
    "            if file.lower() == 'ysite-t_output.xlsx':\n",
    "                excel_file_path = os.path.join(subdir, file)\n",
    "                print(f\"Plotting data from {excel_file_path}\")\n",
    "\n",
    "                # 读取Excel文件并绘图\n",
    "                plot_data_from_excel(excel_file_path, subdir)\n",
    "\n",
    "\n",
    "def plot_data_from_excel(excel_file_path, subdir):\n",
    "    # 读取Excel文件\n",
    "    processed_data = pd.read_excel(excel_file_path)\n",
    "    markers = ['o', 's', '^', 'D', '*', 'P']\n",
    "    # 定义每隔多少度添加一个标记\n",
    "    mark_every = 100\n",
    "\n",
    "    plt.figure(figsize=(12, 8))\n",
    "\n",
    "    # 画出每个数据系列，并添加等距的不同标记\n",
    "    for i, column in enumerate(processed_data.columns[1:]):  # 跳过'T'列\n",
    "        plt.plot(processed_data['T'], processed_data[column], label=column,\n",
    "                 marker=markers[i % len(markers)], markevery=mark_every)\n",
    "\n",
    "    # 添加图例，调整位置到右侧\n",
    "    plt.legend(loc='center left', bbox_to_anchor=(1, 0.8), fontsize=18)\n",
    "    plt.xticks(fontsize=20)\n",
    "    plt.yticks(fontsize=20)\n",
    "    # 添加标题和坐标轴标签\n",
    "    plt.title('Site Occupying Fraction vs. Temperature', fontsize=20)\n",
    "    plt.xlabel('Temperature, K', fontsize=20)\n",
    "    plt.ylabel('Site Occupying Fraction', fontsize=20)\n",
    "    # 调整布局以防止保存图像时切割\n",
    "    plt.tight_layout()\n",
    "\n",
    "    # 保存图像\n",
    "    output_image_path = excel_file_path.replace('_output.xlsx', '.png')\n",
    "    plt.savefig(output_image_path)\n",
    "    plt.close()\n",
    "    print(f\"Plot saved to {output_image_path}\")\n",
    "\n",
    "\n",
    "# 设置根目录路径\n",
    "root_directory = r'.'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# 第一步：处理EXP文件并保存为Excel\n",
    "process_exp_and_save_excel(root_directory)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# 第二步：在需要时执行绘图\n",
    "plot_from_excel_and_save(root_directory)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.7.13 ('base')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.13"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "19d1d53a962d236aa061289c2ac16dc8e6d9648c89fe79f459ae9a3493bc67b4"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
